package com.damage.business_dept.oa.makePurchasePlan;

import com.damage.business_dept.service.IPurchasePlanAuditSerivce;
import com.damage.common.config.PurchasePlanConfig;
import com.damage.common.dto.AuditResult;
import com.damage.common.entity.PurchasePlan;
import com.damage.common.oa.makePurchasePlan.MakePurchasePlanConfig;
import com.damage.common.service.IPublicService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AuditService {

    @Autowired
    private IPublicService publicService;

    @Autowired
    private IPurchasePlanAuditSerivce purchasePlanAuditSerivce;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Transactional
    public PurchasePlan auditPurchasePlan(String taskId, AuditResult auditResult){
        //关联业务实体
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        String businessKey = processInstance.getBusinessKey();

        //审核采购计划
        purchasePlanAuditSerivce.audit(Integer.parseInt(businessKey),auditResult);

        Integer result = auditResult.getResult();
        if (result == PurchasePlanConfig.AUDITED_PASS){
            taskService.setVariable(taskId, MakePurchasePlanConfig.AUDIT_PASS,true);
        }else{
            taskService.setVariable(taskId,MakePurchasePlanConfig.AUDIT_PASS,false);
        }
        taskService.complete(taskId);

        PurchasePlan purchasePlan = publicService.findPurchasePlanById(Integer.parseInt(businessKey));
        return purchasePlan;
    }
}
